/**
* Accenture LLP
* Trigger : UpdateQuotaOnSplitOpty
* Object: QuotaManagement__c
* Description : This Trigger will used to populte Quota Id on Opportunity Split record. 
*
*/

trigger OORTelesalesUpdateQuotaOnSplitOpty on QuotaManagement__c (after insert) {

// Define list variable for  OSplit
List<Opportunity_Split__c> OSplit = new List<Opportunity_Split__c>();
Map<String,QuotaManagement__c> quotaMap = New Map<String,QuotaManagement__c>();
Map<Id,Date> quotaIdmap = New Map<Id,Date>();
Set<Id> splitOwnerSet = new Set<Id>();

if(trigger.isInsert){        

// Loop for to retrive Quota record from trigger
  for(QuotaManagement__c quota : trigger.new){       
             Integer quoteYear=0;
             Integer quoteMonth=0;
             if(quota.QuotaDate__c!=null){
             quoteYear = quota.QuotaDate__c.Year();  
             quoteMonth = quota.QuotaDate__c.Month();
             }           
             String mapKey= quota.MC__c +'_'+ quoteMonth +'_'+ quoteYear; 
             quotaMap.put(mapKey,quota);
             splitOwnerSet.add(quota.MC__c);
             quotaIdmap.put(quota.MC__c,quota.QuotaDate__c);    
             System.debug('mapKey'+mapKey);
                                                     
  }
  
  Integer i=0;
     For (Opportunity_Split__c oppSplit : [select Id,   QuotaManagement__c,Booked_Date__c,Owner_ID__c from Opportunity_Split__c  where Owner_ID__c IN:splitOwnerSet]){                   
                                       
                   If(oppSplit.Booked_Date__c !=null){
                    
                    Integer splitMonth = oppSplit.Booked_Date__c.Month();  
                    Integer splitYear = oppSplit.Booked_Date__c.Year();
                    //System.debug('splitYear'+splitYear);
                    //System.debug('splitMonth'+splitMonth);
                    String splitmapKey= oppSplit.Owner_ID__c +'_'+ splitMonth +'_'+ splitYear;                    
                    //System.debug('splitmapKey'+splitmapKey);
                        if(quotaMap.get(splitmapKey)!=null){
                                                          
                            if(quotaMap.get(splitmapKey).QuotaDate__c.year()== oppSplit.Booked_Date__c.year() 
                            && quotaMap.get(splitmapKey).QuotaDate__c.Month()== oppSplit.Booked_Date__c.Month())
                            {                               
                                oppSplit.QuotaManagement__c  =quotaMap.get(splitmapKey).id ;
                                OSplit.add(oppSplit);
                                
                            }
                       
                       }
                   }          
     }   try{
                Update  OSplit;}        
      catch(exception ex){
      GeneralConstants.mailAnyExceptionToMe('UpdateQuotaOnSplitOpty','Update Quota',ex);    }
    
   }

}